﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace OneWorks.Web.Common.BaiDu.Translate
{
    /// <summary>
    /// 语言类型
    /// </summary>
    public enum LanguageType
    {
        自动识别,
        中,
        英
    }

    /// <summary>
    /// 百度翻译API请求
    /// </summary>
    public class TranslateRequest
    {
        /// <summary>
        /// 开发者在百度开发者中心（右上角“快速创建应用”）注册得到的授权API key	
        /// </summary>
        public string ClientID;

        /// <summary>
        /// 源语言语种：语言代码或auto
        /// </summary>
        public LanguageType From;

        /// <summary>
        /// 源语言语种：语言代码或auto
        /// </summary>
        public LanguageType To;

        /// <summary>
        /// 待翻译内容	 该字段必须为UTF-8编码，并且以GET方式调用API时，需要进行urlencode编码。
        /// </summary>
        public string Query;


        private readonly Dictionary<LanguageType, string> _languages = new Dictionary<LanguageType, string>
            {
                {LanguageType.自动识别, "auto"},
                {LanguageType.中, "zh"},
                {LanguageType.英, "en"}
            };

        public override string ToString()
        {
            if (string.IsNullOrWhiteSpace(ClientID))
                throw new ArgumentException(BaiduErrorMessages.NotKey);

            string s = "client_id=" + ClientID;

            s += "&q=" + System.Web.HttpUtility.UrlEncode(Query);

            s += "&from=" + _languages[From];

            s += "&to=" + _languages[To];

            return s;
        }
    }

    public class TranslateResponse
    {
        /// <summary>
        /// 
        /// </summary>
        [JsonProperty(PropertyName = "from")]
        public string From { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [JsonProperty(PropertyName = "to")]
        public string To { get; set; }

        [JsonProperty(PropertyName = "query")]
        public string Query;

        /// <summary>
        /// 
        /// </summary>
        [JsonProperty(PropertyName = "trans_result")]
        public List<TranslateResult> Results;

        [JsonProperty(PropertyName = "error_code")]
        public TranslateError ErrorCode;

        [JsonProperty(PropertyName = "error_msg")]
        public string ErrorMsg;
    }

    public class TranslateResult
    {
        /// <summary>
        /// 原文
        /// </summary>
        [JsonProperty(PropertyName = "src")]
        public string Src { get; set; }

        /// <summary>
        /// 译文
        /// </summary>
        [JsonProperty(PropertyName = "dst")]
        public string Dst { get; set; }
    }

    public enum TranslateError
    {
        超时 = 52001,
        翻译系统错误 = 52002,
        未授权的用户 = 52003
    }

}
